<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="620px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="代理商名称" prop="agentName">
        <el-input
          v-model="formData.agentName"
          maxlength="30"
          placeholder="请输入姓名"
          :disabled="isView"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="mobile">
        <el-input v-model="formData.mobile" type="text" placeholder="请输入手机号码" :disabled="isView" @input="handleMobileInput" />
      </el-form-item>
      <el-form-item label="登录账号" prop="username">
        <el-input
          v-model="formData.username"
          maxlength="30"
          placeholder="请输入登录代理商后台的账号"
          :disabled="isView"
        />
      </el-form-item>
      <el-form-item label="登录密码" prop="password" :required="!isEdit">
        <el-input
          v-model="formData.password"
          maxlength="30"
          :placeholder="isEdit ? '为空则不修改原密码' : '请输入密码'"
          :disabled="isView"
          type="password"
        />
      </el-form-item>
      <el-form-item label="到期时间" prop="expiredTime">
        <el-date-picker
          v-model="formData.expiredTime"
          type="date"
          placeholder="选择日期"
          value-format="YYYY/MM/DD"
          :disabled-date="disabledDate"
          :disabled="isView"
        />
      </el-form-item>
      <el-form-item label="代理商类型" prop="type">
        <el-select
          v-model="formData.type"
          placeholder="请选择代理商类型"
          @change="handleTypeChange"
          :disabled="isView"
        >
          <el-option label="省级代理商" value="Provincial" />
          <el-option label="市级代理商" value="Municipal" />
          <el-option label="区级代理商" value="District" />
        </el-select>
      </el-form-item>
      <el-form-item label="代理商地址" prop="address">
        <el-cascader
          v-model="formData.address"
          :options="filteredAddressOptions"
          :props="{
            checkStrictly: true,
            value: 'id',
            label: 'name',
            children: 'children',
            emitPath: true
          }"
          :disabled="isView || !formData.type"
          placeholder="请选择地址"
          @change="handleAddressChange"
        />
      </el-form-item>
      <el-form-item label="代理商合同" prop="contractUrl">
        <el-upload
          ref="uploadref"
          class="upload-demo"
          :action="uploadUrl"
          :auto-upload="false"
          :http-request="httpRequest"
          :on-error="onUploadError"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :before-upload="beforeUpload"
          :file-list="fileList"
          accept=".pdf,.jpg,.jpeg,.png,.doc,.docx"
          :disabled="isView"
        >
          <template #trigger>
            <el-button type="primary" :disabled="isView">选择文件</el-button>
          </template>
          <template #file="{ file }">
            <el-tooltip :content="file.name" placement="top">
              <span class="file-name-ellipsis">{{ file.name }}</span>
            </el-tooltip>
          </template>
          <template #tip>
            <div class="el-upload__tip"> 支持上传Word、PDF或图片格式文件 </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="账号状态" prop="status">
        <el-radio-group v-model="formData.status" :disabled="isView">
          <el-radio :value="0">启用</el-radio>
          <el-radio :value="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ isView ? '关闭' : '取消' }}</el-button>
        <el-button v-if="!isView" type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { formateDateday } from '@/utils/formatTime'
import { createAgent, updateAgent } from '@/api/mall/agent/index'
// import { useUploadToWebDisk } from '@/views/ai/webdisk/upload'
import { getAreaTree } from '@/api/system/area/index'
import { useUpload } from '@/components/UploadFile/src/useUpload'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'add'
  },
  currentRow: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const dialogVisible = ref(props.modelValue)
const formRef = ref<FormInstance>()
const fileList = ref<{ name: string; url: string }[]>([])

// 使用上传组件的钩子
const { uploadUrl, httpRequest } = useUpload((percentage: number) => {
  // 这里可以处理上传进度
})

// 计算属性
const isView = computed(() => props.type === 'view')
const isEdit = computed(() => props.type === 'edit')
const dialogTitle = computed(() => {
  const titles = {
    add: '新增代理商',
    edit: '编辑代理商',
    view: '查看代理商'
  }
  return titles[props.type as keyof typeof titles]
})

// 表单数据
const formData = ref({
  agentName: '',
  mobile: '',
  username: '',
  password: '',
  expiredTime: '',
  type: '',
  address: [] as (string | number)[],
  contractUrl: '',
  status: 0
})
// 表单验证规则
const rules = reactive<FormRules>({
  agentName: [{ required: true, message: '请输入代理商名称', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  username: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  password: [{
    required: true,
    message: '请输入登录密码',
    trigger: 'blur',
    validator: (rule, value, callback) => {
      if (props.type === 'add' && (!value || value.trim() === '')) {
        callback(new Error('请输入登录密码'))
      } else {
        callback()
      }
    }
  }],
  expiredTime: [{ required: true, message: '请选择到期时间', trigger: 'change' }],
  type: [{ required: true, message: '请选择代理商类型', trigger: 'change' }],
  address: [
    {
      required: true,
      message: '请选择代理商地址',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请选择代理商地址'))
          return
        }

        const typeLevelMap = {
          Provincial: 1, // 省级
          Municipal: 2, // 市级
          District: 3  // 区级
        }
        
        const requiredLevel = typeLevelMap[formData.value.type as keyof typeof typeLevelMap]
        // 检查选择的地址层级是否正确
        if (requiredLevel && value.length !== requiredLevel) {
          const levelText = formData.value.type === 'Provincial' 
            ? '省级' 
            : formData.value.type === 'Municipal' 
              ? '市级' 
              : '区级'
          callback(new Error(`请选择到${levelText}`))
          return
        }

        callback()
      }
    }
  ],
  contractUrl: [{ required: true, message: '请上传代理商合同', trigger: 'change' }]
})

// 地址选项（示例数据，实际使用时需要替换为真实数据）
const addressOptions = ref([])

// 根据代理商类型过滤地址选项
const filteredAddressOptions = computed(() => {
  if (!formData.value.type || !addressOptions.value.length) return []
  
  // 根据代理商类型过滤地址树
  const cloneOptions = JSON.parse(JSON.stringify(addressOptions.value))
  
  if (formData.value.type === 'Provincial') {
    // 省级代理商，只需要省级选项，不显示子节点
    return cloneOptions.map(province => ({
      ...province,
      children: [] // 不显示子节点
    }))
  } else if (formData.value.type === 'Municipal') {
    // 市级代理商，需要省和市级选项，不显示区级
    return cloneOptions.map(province => ({
      ...province,
      children: province.children ? province.children.map(city => ({
        ...city,
        children: [] // 不显示区级节点
      })) : []
    }))
  }
  
  // 区级代理商，显示完整的地址树
  return cloneOptions
})

// 禁用今天之前的日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 文件上传前的验证
const beforeUpload = (file: any) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 处理超出文件数量限制
// const handleExceed = (files: any) => {
//   console.log('2025年06月16日13:-------++++', files)
//   // ElMessage.warning('只能上传一个文件，请先删除已有文件')
// }

// 处理文件变化
const handleFileChange = async (file: any) => {
  if (!beforeUpload(file.raw)) return
  const newFile = file.raw
  const obj: any = {
    file: newFile
  }
  const res: any = await httpRequest(obj)
  fileList.value = [
    {
      name: file.raw.name,
      url: res.data.data
    }
  ]
  formData.value.contractUrl = res.data
}

// 处理文件删除
const handleFileRemove = () => {
  fileList.value = []
  formData.value.contractUrl = ''
}

// 处理上传错误
const onUploadError = (err: Error) => {
  ElMessage.error('上传失败: ' + err.message)
}

// 定义地区对象接口
interface AreaItem {
  id: string | number;
  name: string;
  children?: AreaItem[];
  [key: string]: any;
}

// 获取代理商详情
const getAgentInfo = async () => {
  // [{agentArea: "130203"
  // agentAreaName: "路北区"
  // fullName: "河北省唐山市路北区"
  // level:4}]
  try {
    const data = props.currentRow
    // 确定代理商类型
    const agentType = data.areaLevels[0].level === 2
      ? 'Provincial'
      : data.areaLevels[0].level === 3
        ? 'Municipal'
        : 'District'
    
    // 先设置代理商类型，这样会触发地址选项的过滤
    formData.value.type = agentType
    
    // 设置表单数据
    Object.assign(formData.value, {
      agentName: data.agentName,
      mobile: data.mobile,
      username: data.username,
      expiredTime: formateDateday(data.expiredTime || ''),
      type: agentType,
      status: data.status
    })

    // 根据区域编码异步设置地址
    setAddressByCode(data.areaLevels[0].agentArea, agentType)
    
    // 如果有合同文件，设置文件列表
    if (data.contractUrl) {
      fileList.value = [
        {
          name: data.contractUrl || '合同文件',
          url: data.contractUrl
        }
      ]
      formData.value.contractUrl = data.contractUrl
    }
  } catch (error) {
    console.error('获取代理商详情失败:', error)
    ElMessage.error('获取代理商详情失败')
  }
}

// 根据区域编码设置地址
const setAddressByCode = async (areaCode: string, agentType: string) => {
  // 如果地址选项还没加载完，等待加载
  if (!addressOptions.value || addressOptions.value.length === 0) {
    await getAreaTreeData()
  }
  
  const addressIds: (string | number)[] = []
  
  try {
    // 根据代理商类型和区域编号查找对应的地址ID
    if (agentType === 'Provincial') {
      // 省级，只需要找到省ID
      const provinceCode = areaCode.substring(0, 2) + '0000'
      // 遍历查找匹配的省份
      for (const province of addressOptions.value as AreaItem[]) {
        if (province.id?.toString() === provinceCode) {
          addressIds.push(province.id)
          break
        }
      }
    } else if (agentType === 'Municipal') {
      // 市级，需要找到省ID和市ID
      const provinceCode = areaCode.substring(0, 2) + '0000'
      const cityCode = areaCode.substring(0, 4) + '00'
      
      // 遍历查找匹配的省份
      for (const province of addressOptions.value as AreaItem[]) {
        if (province.id?.toString() === provinceCode) {
          addressIds.push(province.id)
          
          // 遍历查找匹配的城市
          if (province.children && province.children.length > 0) {
            for (const city of province.children as AreaItem[]) {
              if (city.id?.toString() === cityCode) {
                addressIds.push(city.id)
                break
              }
            }
          }
          break
        }
      }
    } else {
      // 区级，需要找到省ID、市ID和区ID
      const provinceCode = areaCode.substring(0, 2) + '0000'
      const cityCode = areaCode.substring(0, 4) + '00'
      
      // 遍历查找匹配的省份
      for (const province of addressOptions.value as AreaItem[]) {
        if (province.id?.toString() === provinceCode) {
          addressIds.push(province.id)
          
          // 遍历查找匹配的城市
          if (province.children && province.children.length > 0) {
            for (const city of province.children as AreaItem[]) {
              if (city.id?.toString() === cityCode) {
                addressIds.push(city.id)
                
                // 遍历查找匹配的区县
                if (city.children && city.children.length > 0) {
                  for (const district of city.children as AreaItem[]) {
                    if (district.id?.toString() === areaCode) {
                      addressIds.push(district.id)
                      break
                    }
                  }
                }
                break
              }
            }
          }
          break
        }
      }
    }
    
    // 设置地址
    if (addressIds.length > 0) {
      formData.value.address = addressIds
    }
  } catch (error) {
    console.error('设置地址失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  // 登录账号：用户账号由 数字、字母 组成
  if(formData.value.username){
    const testUsername = /^[a-zA-Z0-9]+$/.test(formData.value.username)
    if(!testUsername){
      ElMessage.warning('登录账号只能由数字、字母组成')
      return
    }
  }

    
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      const sendData = {
        agentName: formData.value.agentName,
        mobile: formData.value.mobile,
        username: formData.value.username,
        password: formData.value.password,
        expiredTime: new Date(formData.value.expiredTime).getTime(),
        status: formData.value.status,
        contractUrl: formData.value.contractUrl,
        agentAreaCode: String(formData.value.address[formData.value.address.length - 1]),
        level:
          formData.value.type === 'Provincial' ? 2 : formData.value.type === 'Municipal' ? 3 : 4
      }
      // console.log('2025年07月02日13:51:36+++', sendData)
      // return
      try {
        if (props.type === 'add') {
          await createAgent(sendData)
          ElMessage.success('添加成功')
        } else if (props.type === 'edit') {
          // 如果是编辑状态且密码为空，则不发送密码字段
          if (!formData.value.password) {
            const { password, ...rest } = sendData
            await updateAgent({ ...rest, id: props.currentRow.id })
          } else {
            await updateAgent({ ...sendData, id: props.currentRow.id })
          }
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        emit('success')
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 关闭弹窗
const handleClose = () => {
  emit('update:modelValue', false)
  formRef.value?.resetFields()
  fileList.value = []
  // 重置表单数据
  Object.assign(formData.value, {
    agentName: '',
    mobile: '',
    username: '',
    password: '',
    expiredTime: '',
    type: '',
    address: [],
    contractUrl: '',
    status: 0
  })
}

// 监听弹窗显示状态
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val
    if (val && props.type !== 'add') {
      getAgentInfo()
    }
  }
)



watch(
  () => dialogVisible.value,
  (val) => {
    emit('update:modelValue', val)
  }
)

// 处理代理商类型变化
const handleTypeChange = (value: string) => {
  // 清空已选择的地址
  formData.value.address = []
}

// 只允许输入数字的处理函数
const handleMobileInput = () => {
  formData.value.mobile = formData.value.mobile.replace(/[^\d]/g, '');
}

// 处理地址选择变化
const handleAddressChange = (value: any) => {
  if (!value || !formData.value.type) return

  // 省级代理商只能选一级，市级代理商只能选两级，区级代理商可以选三级
  const typeLevelMap = {
    Provincial: 1,
    Municipal: 2,
    District: 3
  }

  const maxLevel = typeLevelMap[formData.value.type as keyof typeof typeLevelMap]
  // 由于我们已经在filteredAddressOptions中限制了层级，这里只是额外检查
  if (value.length > maxLevel) {
    formData.value.address = value.slice(0, maxLevel)
  }
}
// 获取地址树
const getAreaTreeData = async () => {
  const list = await getAreaTree()
  addressOptions.value = list
}
onMounted(() => {
  getAreaTreeData()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.file-name-ellipsis {
  display: inline-block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
</style>
